<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2018/1/9
 * Time: 下午3:39
 */

namespace Biz\model\trade;

use Biz\tools\OrderNo as toolOrderNo;
use Biz\tools\ShopArea as toolShopArea;
use Medoo\Medoo;
use Biz\pockets\constInterface\TheParagraphStore;


class Order extends \Doraemon\pockets\datebase\BaseDbModel
{
    const _CONFIG_FILE_ = 'db_shop';

    const _CONFIG_SELECT_ = 'db_trade';

    const _DATABASE_ = 'shop_trade';

    const _TABLE_NAME = 'order(o)';

    const MAX_CREATE_ORDER_GOODS_NUM = 50;//最大下单商品数量50个
    const MAX_CREATE_ORDER_AMOUNT = 50000;//最大下单金额5万

    //最长确认收货时间
    const MAX_WAIT_PAY_TIME = 60 * 60;//60分钟不支付，自动取消订单
    const MAX_WAIT_AUTO_CONFIRM_TIME = 15 * 86400;//15天后自动确认收货
    //最大可以在自动收货时间的基础上延长的时间
    const MAX_WAIT_PROLONG_TIME = 3 * 86400;//3天

    //多少天是无理由退换
    const MAX_REFUND_GOODS_DAYS_WITH_NO_REASON = 7 * 86400;//7天

    //确认收货后申请退款的结束时间 15天内
    const MAX_WAIT_REFUND_TIME = 15 * 86400;

    //订单类型
    const ORDER_TYPE_NORMAL = 0;//普通订单
    const ORDER_TYPE_GROUP_BUY = 1;//团购订单
    const ORDER_TYPE_PING_TUAN = 2;//拼团订单

    //取消订单的类型
    const CANCEL_TYPE_HANDLE = 1;//手动取消
    const CANCEL_TYPE_SYSTEM = 2;//自动取消


    //是否分包裹发货
    const IS_PACKAGE_DELIVERY_YES = 1;//是
    const IS_PACKAGE_DELIVERY_NO = 0;//否

    //订单结算来源（购物车，立即购买）
    const SOURCE_CART = 1;//购物车
    const SOURCE_DETAIL = 2;//立即购买

    //订单下单来源
    const FROM_SOURCE_APP = 1;//好好住app
    const FROM_SOURCE_WX_MINI = 2;//微信好好住商城小程序
    const FROM_SOURCE_TUAN_MINI = 3;//微信团购小程序
    const FROM_SOURCE_PARAGRAPH_MINIPROGRAM = 4;//微信节选小程序

    const FROM_SOURCE_PARAGRAPH_MINIPROGRAM_SH = TheParagraphStore::STORE_SH;//微信节选小程序SH
    const FROM_SOURCE_PARAGRAPH_MINIPROGRAM_BJ = TheParagraphStore::STORE_BJ;//微信节选小程序BJ

    //pay_way的值
    const PAY_WAY_ALIPAY_APP = 'alipay';//支付宝APP支付
    const PAY_WAY_WXPAY_APP = 'wechat';//微信APP支付

    public static $fromSource = [
        self::FROM_SOURCE_APP => '好好住APP',
        self::FROM_SOURCE_WX_MINI => '微信小程序',
        self::FROM_SOURCE_TUAN_MINI => '微信团购小程序',
        self::FROM_SOURCE_PARAGRAPH_MINIPROGRAM => '节选小程序',
        self::FROM_SOURCE_PARAGRAPH_MINIPROGRAM_SH => '节选小程序-SH',
        self::FROM_SOURCE_PARAGRAPH_MINIPROGRAM_BJ => '节选小程序-BJ'
    ];

    public static $payWayDesc = [
        self::PAY_WAY_ALIPAY_APP => '支付宝APP支付',
        self::PAY_WAY_WXPAY_APP => '微信APP支付',
    ];

    //订单退款流转状态
    const REFUNDING_STATUS_NORMAL = 0;//该订单无退款申请
    const REFUNDING_STATUS_PROCESS = 1;//该订单有退款记录


    //订单状态
    const STATUS_NORMAL = 10;//订单已创建（待付款）

    const STATUS_WAIT_SEND = 20;//待发货
    const STATUS_SEND_OUT = 21;//已发货

    const STATUS_SEND_PART_OUT = 22;//部分发货

    const STATUS_SUCCESS = 30;//交易成功（已完成）
    const V_STATUS_WAIT_COMMENT = 31;//待评价（虚拟状态请勿插入数据库）
    const V_STATUS_COMMENTED = 32;//已评价（虚拟状态请勿插入数据库）

    const STATUS_CLOSE = 60;//交易关闭

    const STATUS_DEL = 90;//已删除


    const COMMENT_STATUS_NORMAL = 1; //已评价
    const COMMENT_STATUS_NO = 0; //未评价


    public static $cancelTypeDesc = [
        self::CANCEL_TYPE_HANDLE => '手工取消',
        self::CANCEL_TYPE_SYSTEM => '系统自动取消'
    ];


    //订单取消理由
    const CANCEL_REASON_1 = 1;
    const CANCEL_REASON_2 = 2;
    const CANCEL_REASON_3 = 3;
    const CANCEL_REASON_4 = 4;
    const CANCEL_REASON_5 = 5;
    const CANCEL_REASON_6 = 6;
    const CANCEL_REASON_7 = 7;


    public static $cancelReasonDesc = [
        self::CANCEL_REASON_1 => '发货时间太长',
        self::CANCEL_REASON_2 => '操作有误(商品、地址选错)',
        self::CANCEL_REASON_3 => '重复下单/误下单',
        self::CANCEL_REASON_4 => '其他渠道价格更低',
        self::CANCEL_REASON_5 => '不想买了',
        self::CANCEL_REASON_6 => '商品无货',
        self::CANCEL_REASON_7 => '其他原因'
    ];


    public static $commentStatusDesc = [
        self::COMMENT_STATUS_NORMAL => '已评价',
        self::COMMENT_STATUS_NO => '未评价'
    ];


    public static $statusDesc = [
        self::STATUS_NORMAL => '待付款',
        self::STATUS_WAIT_SEND => '待发货',
        self::STATUS_SEND_OUT => '待收货',
        self::STATUS_SEND_PART_OUT => '待收货',
        self::STATUS_SUCCESS => '交易成功',
        self::STATUS_CLOSE => '交易关闭',
        self::STATUS_DEL => '已删除'
    ];

    public static $statusMgtDesc = [
        self::STATUS_NORMAL => '待付款',
        self::STATUS_WAIT_SEND => '待发货',
        self::STATUS_SEND_OUT => '待确认收货',
        self::STATUS_SEND_PART_OUT => '部分发货',
        self::STATUS_SUCCESS => '交易成功',
        self::STATUS_CLOSE => '交易关闭',
        self::STATUS_DEL => '已删除'
    ];

    public static $statusAdmDesc = [
        self::STATUS_NORMAL => '待付款',
        self::STATUS_WAIT_SEND => '待发货',
        self::STATUS_SEND_OUT => '全部发货待确认',
        self::STATUS_SEND_PART_OUT => '部分发货待确认',
        self::STATUS_SUCCESS => '交易成功',
        self::STATUS_CLOSE => '交易关闭',
        self::STATUS_DEL => '已删除'
    ];

    public static $vStatusDesc = [
        self::V_STATUS_WAIT_COMMENT => '待评价',
        self::V_STATUS_COMMENTED => '已评价',
    ];


    //已支付过订单的状态合集
    public static $paiedStatusList = [
        self::STATUS_WAIT_SEND => '待发货',
        self::STATUS_SEND_OUT => '已发货',
        self::STATUS_SEND_PART_OUT => '部分发货',
        self::STATUS_SUCCESS => '交易成功',
    ];

    public static $canDeleteStatusList = [
        self::STATUS_SUCCESS => '交易成功',
        self::STATUS_CLOSE => '交易关闭',
    ];

    public static $canChangeAddressStatusList = [
        self::STATUS_NORMAL => '待付款',
        self::STATUS_WAIT_SEND => '待发货',
    ];


    public static function checkStatusCanPay($orderStatus)
    {
        if ($orderStatus == self::STATUS_NORMAL) {
            return true;
        }

        return false;
    }

    public static function checkStatusCanShip($orderStatus)
    {
        if ($orderStatus == self::STATUS_WAIT_SEND || $orderStatus == self::STATUS_SEND_PART_OUT) {
            return true;
        }
        return false;
    }

    public static function checkStatusCanChangeAddress($orderStatus)
    {
        if (key_exists($orderStatus, self::$canChangeAddressStatusList)) {
            return true;
        }
        return false;
    }

    public static function checkStatusCanConfirmReceipt($orderStatus)
    {
        if ($orderStatus == self::STATUS_SEND_OUT) {
            return true;
        }
        return false;
    }

    public static function checkStatusCanDelete($orderStatus)
    {
        if (key_exists($orderStatus, self::$canDeleteStatusList)) {
            return true;
        }
        return false;
    }

    public static function checkStatusCanProlong($orderStatus)
    {
        if (in_array($orderStatus, [self::STATUS_SEND_OUT])) {
            return true;
        }
        return false;
    }

    public static function checkOrderCanProlong($prolongTime)
    {
        if ($prolongTime == '0000-00-00 00:00:00') {
            return true;
        }
        return false;
    }

    public static function getOrderNoList($orderNo)
    {

        $isParentOrder = toolOrderNo::isParentNo($orderNo);

        if (!$isParentOrder) {

            return [$orderNo];
        }

        $list = self::select('order_no', ['order_parent_no' => $orderNo]);

        return $list;
    }

    public static function getPaiedOrderInfoByParentOrderNo($orderNo)
    {
        $orderNos = self::select('*', [
            'order_parent_no' => $orderNo,
            'status' => array_keys(self::$paiedStatusList)
        ]);
        return $orderNos;
    }

    public static function getOrderInfoFromMaster($orderNo)
    {

        $info = self::select_master("*", Medoo::raw(' where order_no=:orderNo for update', [':orderNo' => $orderNo]));

        $info = array_shift($info);


        if (empty($info)) {
            return false;
        }

        self::formatInfo($info);


        return $info;
    }

    public static function getOrderInfo($orderNo, $uid = 0)
    {
        $where = ['order_no' => $orderNo];
        if ($uid !== 0) {
            $where['uid'] = $uid;
        }
        $info = self::get('*', $where);

        if (empty($info)) {
            return false;
        }

        self::formatInfo($info);

        return $info;
    }

    public static function getOrderParentNo($orderNo)
    {
        $info = self::getOrderInfo($orderNo);

        if (!empty($info)) {
            return $info['order_parent_no'];
        }

    }

    public static function getOrderInfoList(array $where, $limit = [], $order = [], $format = true, $select = "*")
    {
        if ($limit) {
            $where["LIMIT"] = $limit;
        }
        if ($order) {
            $where['ORDER'] = $order;
        }
        $list = self::select($select, $where);
        if (!$list) {
            return false;
        }

        if ($format) {
            foreach ($list as &$info) {
                self::formatInfo($info);
            }
        }

        return $list;
    }

    public static function getOrderInfoListCount(array $where)
    {
        return self::count('*', $where);
    }

    public static function formatInfo(&$info)
    {
        if (empty($info))
            return;
        foreach ($info as $key => $value) {
            switch ($key) {
                case 'consignee_province':
                    $area = toolShopArea::locationId2Array($info['consignee_province'] . ',' . $info['consignee_city']);
                    $info['consignee_province_desc'] = isset($area[0]) ? $area[0] : '';
                    $info['consignee_city_desc'] = isset($area[1]) ? $area[1] : '';
                    break;
                case 'shipping_amount':
                    $info['shipping_amount_desc'] = $value > 0 ? $value : '免邮';
                    break;
                case 'status':
                    $info['status_desc'] = self::$statusDesc[$value];
                    if ($info['status'] == self::STATUS_SUCCESS) {
                        if ($info['is_commented']) {
                            $info['v_status'] = self::V_STATUS_COMMENTED;
                        } else {
                            $info['v_status'] = self::V_STATUS_WAIT_COMMENT;
                        }
                    } else {
                        $info['v_status'] = $info['status'];
                    }
                    break;
                case 'delivery_time':
                    if ($info['status'] == self::STATUS_SEND_OUT) {
                        if ($info['prolong_time'] == '0000-00-00 00:00:00') {
                            $info['maxprolong_time'] = date('Y-m-d H:i:s', strtotime($info['autoconfirm_time']) + self::MAX_WAIT_PROLONG_TIME);
                        } else {
                            $info['autoconfirm_time'] = $info['prolong_time'];
                            $info['maxprolong_time'] = $info['prolong_time'];
                        }
                    }
                    break;

            }
        }
    }


    public static function insertOrder($data)
    {
        return self::insert($data)->rowCount();
    }

    public static function selectOrderByOrderNo($orderNo)
    {
        return self::select('*', ['order_no' => $orderNo]);
    }

    public static function getOrderByOrderNo($orderNo)
    {
        if (empty($orderNo)) {
            throw new \Exception('订单号不能为空', 0);
        }
        return self::get('*', ['order_no' => $orderNo]);
    }

    //待付款订单可以留言
    public static function modifyMessage($uid, $orderNo, $content)
    {
        self::update(['message' => $content], [
            'uid' => $uid,
            'order_no' => $orderNo,
            'status' => self::STATUS_NORMAL
        ]);
    }

    public static function updateData($data, $where)
    {
        return self::update($data, $where)->rowCount();
    }

    public static function getOrderByWhere($method, $fields, $where)
    {
        return self::$method($fields, $where);
    }

}